<?php

namespace app\admin\controller\choi;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;

/**
 * 教师课程管理
 *
 * @icon fa fa-circle-o
 */
class TeacherCourse extends Backend
{
    
    /**
     * TeacherCourse模型对象
     * @var \app\admin\model\choi\TeacherCourse
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\choi\TeacherCourse;
        $this->assign('teacherList', \app\admin\model\choi\Teacher::all());
        $this->assign('languageList', \app\admin\model\choi\Language::all());
        $this->assign('languageGradeList', \app\admin\model\choi\LanguageGrade::all());

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['teacher', 'language', 'languageGrade'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['teacher', 'language', 'languageGrade'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);


            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $course = $this->model->find($ids);
            if (!$course) {
                $this->error(__('课程不存在'));
            }
            $teacher = \app\admin\model\choi\Teacher::find($course->teacher_id);
            if (!$teacher || $teacher->verify != 2) {
                $this->error(__('教师还未实名认证，请先审核该教师'));
            }
            if ($course->recommendswitch) {
                $course->recommendswitch = 0;
            } else {
                $course->recommendswitch = 1;
            }
            $res = $course->save();
            $res ? $this->success() : $this->error(__('服务器异常，请联系管理员'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
